package com.ruoyi.wx.service;

import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.alibaba.fastjson2.JSONObject;
import com.github.binarywang.wxpay.config.WxPayConfig;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.wx.domain.DyMaForm;
import com.ruoyi.wx.domain.DyMaUser;
import cn.binarywang.wx.miniapp.config.WxMaConfig;
import cn.hutool.http.HttpUtil;

@Component
public class DyMaUserService {
	
	@Autowired
	private IWxAppService wxAppService;

	/**
     * 获取用户信息
     */
	public DyMaUser getUserInfo(DyMaForm dyMaForm){
		String openId = this.jscode2session(dyMaForm);
		if(StringUtils.isBlank(openId)){
			throw new ServiceException("openId不能为空");
		}
		DyMaUser wxMaUser = JSONObject.parseObject(dyMaForm.getRawData(), DyMaUser.class);
		wxMaUser.setAppId(dyMaForm.getAppId());
		wxMaUser.setOpenId(openId);
		return wxMaUser;
	}
	
	public void dyPay(DyMaForm dyMaForm) {
		WxPayConfig payConfig = wxAppService.getPayConfig(dyMaForm.getAppId());
		String url = "https://developer.toutiao.com/api/apps/ecpay/v1/create_order";
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("appid", payConfig.getAppId());
		paramMap.put("out_order_no", dyMaForm.getTradeNo());
		paramMap.put("total_amount", dyMaForm.getTotalFee());
		paramMap.put("subject", dyMaForm.getBody());
		paramMap.put("body", dyMaForm.getBody());
		paramMap.put("valid_time", 180);
		paramMap.put("sign", null);
		paramMap.put("notify_url", dyMaForm.getNotifyUrl());
		String json = HttpUtil.post(url, JSONObject.toJSONString(paramMap));
	}
	
	public String jscode2session(DyMaForm dyMaForm){
		WxMaConfig config = wxAppService.getAppConfig(dyMaForm.getAppId());
		String url = "https://developer.toutiao.com/api/apps/v2/jscode2session";
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("appid", config.getAppid());
		paramMap.put("secret", config.getSecret());
		paramMap.put("code", dyMaForm.getCode());
		paramMap.put("anonymous_code", dyMaForm.getAnonymousCode());
		String json = HttpUtil.post(url, JSONObject.toJSONString(paramMap));
		JSONObject object = JSONObject.parseObject(json);
		JSONObject data = object.getJSONObject("data");
		if(!"0".equals(object.getString("err_no"))){
			throw new ServiceException("抖音授权失败");
		}
		return data.getString("openid");
	}
	
}
